package action.back;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.Dict;
import net.sf.json.JSONArray;

public class DictAction extends DefaultAction {
	
	private Dict dict;
	
	public String index() {
		return "index";
	}
	
	@SuppressWarnings("unchecked")
	public void getTrees() {
		Integer parent_id = Integer.parseInt(request.getParameter("parent_id"));

		List<Dict> dicts;
		if (parent_id == null || parent_id.intValue() == 0) {
			dicts = getCommonService().findAll(Dict.class, "position asc", "parent is null",null);
		} else {
			dicts = getCommonService().findAll(Dict.class, "position asc", "parent.id = ? ",new Object[]{parent_id});
		}

		List<Map> trees = new ArrayList<Map>();
		for (Dict dict : dicts) {
			Map<String, Object> tree = new HashMap<String, Object>();
			tree.put("id", dict.getId());
			tree.put("text", dict.getName());
			tree.put("leaf", dict.getSubDictCount() == 0);
			trees.add(tree);
		}
		
		JSONArray jsonObject = JSONArray.fromObject(trees);
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
		
	}
	
	@SuppressWarnings("unchecked")
	public void getChildren() {
		Integer parent_id = Integer.parseInt(request.getParameter("parent_id"));
	        
	    List<Dict> dicts;
	    if (parent_id == null || parent_id.intValue() == 0) {
			dicts = getCommonService().findAll(Dict.class, "position asc", "parent is null",null);
		} else {
			dicts = getCommonService().findAll(Dict.class, "position asc", "parent.id = ? ",new Object[]{parent_id});
		}
	    List<Map<String, Object>> jsonList = new ArrayList<Map<String,Object>>();
	    for(Dict m : dicts){
	    	Map<String, Object> map = new HashMap<String, Object>();
	    	map.put("dict", m);
	    	
	    	jsonList.add(map);
	    }
	    JSONArray jsonObject = JSONArray.fromObject(jsonList);
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
	}
	


	public void update() {
		getCommonService().update(dict);
		renderJson("{success:true,id:"+dict.getId()+",name:'"+dict.getName()+"'}");
	}
	
	public void create() {
		
		Integer parent_id = Integer.parseInt(request.getParameter("parent_id"));
		if(parent_id>0){
			Dict parent = new Dict();
			parent.setId(parent_id);
			dict.setParent(parent);
		}
		
		//dict.setIfFunc("false");
		getCommonService().save(dict);

		renderJson("{success:true,id:"+dict.getId()+"}");
	}
	
	

	public void delete() {
		for(Integer id : ids){
			//getCommonService().executeUpdate("delete Dict e where e.parent.parent.id = ?", id);
			getCommonService().executeUpdate("delete Dict e where e.parent.id = ?", id);
			getCommonService().executeUpdate("delete Dict where id = ?", id);
		}
		
		renderJson("{success:true}");
	}
	

	public Dict getDict() {
		return dict;
	}

	public void setDict(Dict dict) {
		this.dict = dict;
	}
}
